package com.dunjx.fast.controller;


import com.dunjx.fast.file.FastDFSFile;
import com.dunjx.fast.util.FastDFSClient;
import entity.Result;
import entity.StatusCode;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author 敦佳星
 *
 */
@RestController
@RequestMapping("/file")
public class FileController {


    @RequestMapping("yes")
    public String yes(){
        return "yes";
    }

    @PreAuthorize("hasAnyRole('user')")
    @RequestMapping("no")
    public String no(){
        return "yes";
    }
    @PostMapping("/upload")
    public Result upload(@RequestParam(value = "file",required = false)MultipartFile file) throws IOException {
        if (file == null||file.getSize()==0){
            return new Result(false,StatusCode.ERROR,"请选择要上传的文件");
        }

        //文件上传
        FastDFSFile fastDFSFile = new FastDFSFile(
                file.getOriginalFilename(),
                file.getBytes(),
                //获取文件扩展名
                StringUtils.getFilenameExtension(file.getOriginalFilename())
        );
        String[] upload = FastDFSClient.upload(fastDFSFile);
        String groupId = upload[0];
        String fileNewName = upload[1];
        String trackerUrl = FastDFSClient.getTrackerUrl();
        String path = trackerUrl + "/" + groupId + "/" + fileNewName;
        System.out.println("文件路径为：：：" + path);
        return new Result(true, StatusCode.OK, "上传成功", path);
    }

    /**
     * @param groupName group1
     * @param fileName  M00/00/00/rB8ozmBrIVCAej_XAATllKYVbo0981.png
     * @return
     * @throws IOException
     */
    @PostMapping("/delete")
    public  Result delete(String groupName, String fileName){

        FastDFSClient.deleteFile(groupName, fileName);
        return new Result(true, StatusCode.OK, "删除成功");
    }


    /**
     * @param groupName 组名
     * @param fileName  文件名
     * @param path      保存位置
     * @return
     * @throws IOException
     */
    @PostMapping("/downFile")
    public Result downFile(String groupName, String fileName, String path) throws IOException {

        InputStream is = FastDFSClient.downFile(groupName, fileName);
        byte[] bytes = new byte[1024];
        FileOutputStream os = new FileOutputStream(path);
        while (is.read(bytes) != -1) {
            os.write(bytes);
        }
        os.flush();
        os.close();
        is.close();
        return new Result(true, StatusCode.OK, "下载成功");
    }

}
